package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源映射
        registry.addResourceHandler("/static/**")
                .addResourceLocations("/WEB-INF/static/")
                .setCachePeriod(3600)
                .resourceChain(true);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptorAdapter() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String requestURI = request.getRequestURI();
                
                // 静态资源直接放行
                if (requestURI.contains("/static/")) {
                    return true;
                }
                
                // 登录和注册相关页面直接放行
                if (requestURI.endsWith("login.jsp") || 
                    requestURI.endsWith("register.jsp") || 
                    requestURI.equals("/user/login") || 
                    requestURI.equals("/user/register")) {
                    return true;
                }
                
                // 检查用户是否已登录
                Object user = request.getSession().getAttribute("user");
                if (user == null) {
                    response.sendRedirect(request.getContextPath() + "/login.jsp");
                    return false;
                }
                return true;
            }
        }).excludePathPatterns("/static/**");
    }
} 